import React from 'react';
import { List, Popup, Tabs, WhiteSpace, WingBlank } from 'antd-mobile';
import { connect } from 'dva';
import { createForm } from 'rc-form';
import _ from 'lodash';
import Container from '../components/Base/Container';
import ReactEcharts from '../components/Base/Echarts';
import SortableListHead from '../components/Base/SortableListHead';
import MyIcon from '../components/Base/MyIcon';
import FilterControl from '../components/Base/FilterControl';
import moment from 'moment';
import styles from './PerformancePage.css';
import { routerRedux } from "dva/router";

const TabPane = Tabs.TabPane;
const ListItem = List.Item;


class PerformancePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sValue: ['2013'],
      selectText: '选择连锁店',
      rank1Sort: {
        sort: -1, key: 'value',
      },
      rank2Sort: {
        sort: -1, key: 'value',
      },
    };
  }

  getOption3 = () => {
    const { statBranchRateCurMonth } = this.props;
    if (!statBranchRateCurMonth) return null;

    const months = statBranchRateCurMonth.stat.map((c) => {
      return c.ym;
    });
    const monthData = statBranchRateCurMonth.stat.map((c) => {
      return c.total_money;
    });
    const option = {
      title: {
        // text: '会员增长趋势',
      },
      color: ['#6aa7da'],
      tooltip: {
        trigger: 'axis',
        formatter: ' {b0} <br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgb(101,166,205)"></span>{a0}: {c0}万元',
      },
      grid: {
        containLabel: true,
        left: 10,
        right: 10,
        top: 40,
        bottom: 40,
      },
      legend: {
        // data: ['贡献', '客单价'],
      },
      xAxis: [{
        type: 'category',
        axisTick: {
          alignWithLabel: true,
        },
        data: months,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },

      }],
      yAxis: [{
        type: 'value',
        // position: 'left',
        // splitLine: {show: false},
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        /* axisLabel:{
           //margin:0,
           showMinLabel:false
         },*/

      }],
      series: [
        {
          name: '销售额',
          type: 'line',
          label: {
            normal: {
              show: false,
            },
          },
          lineStyle: {
            normal: {
              color: "#6aa7da",
              width: 1.5,
              //shadowColor: 'rgba(0,0,0,0.4)',
              //shadowBlur: 10,
              //shadowOffsetY: 10,
            },
          },
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgb(228,240,250)', // 0% 处的颜色
                }, {
                  offset: 1, color: 'rgba(228,240,250,0.1)', // 100% 处的颜色
                }],
                globalCoord: false, // 缺省为 false
              },
            },
          },
          // data: [1, 13, 37, 35, 15, 13, 25, 21, 6, 45, 32, 2, 4, 13, 6, 4, 11],
          data: monthData, //[1, 13, 37, 35, 15, 13, 25, 21, 6, 45, 32, 2, 4, 13, 6, 4, 11],
        },
      ],
    };

    return (<ReactEcharts
      option={option}
    />);
  };

  getOption4 = () => {
    const { statBranchRateCurYear } = this.props;
    if (!statBranchRateCurYear) return null;

    const years = statBranchRateCurYear.stat.map((c) => {
      return c._id;
    });
    const yearData = statBranchRateCurYear.stat.map((c) => {
      return c.total_money;
    });

    const option = {
      color: ['#6aa7da', '#ffc000'],
      tooltip: {
        trigger: 'axis',
        formatter: '{b0} <br/> <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgb(194,53,49)"></span>{a0}: {c0}万元',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        // data: ['上月', '本月'],
      },
      grid: {
        containLabel: true,
        left: 10,
        right: 10,
        top: 40,
        bottom: 40,
      },
      xAxis: [
        {
          type: 'category',
          data: years,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: '销售额',
          type: 'bar',
          barWidth: 10,
          label: {
            normal: {
              show: false,
              position: 'top',
            },
          },
          data: yearData,
        },
      ],
    };
    return (<ReactEcharts
      option={option}
    />);
  };
  getOption5 = () => {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      yAxis: [
        {
          type: 'category',
          data: ['美素', '雅培', '帮宝适', '贝亲', '好奇', '合生元'],
        },
      ],
      xAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: '上月',
          type: 'bar',
          label: {
            normal: {
              show: true,
              position: 'inside',
            },
          },
          data: [320, 332, 301, 334, 390, 330],
        },
      ],
    };
    return option;
  };
  onChange = (key) => {
    switch (key) {
      case '2':
        // this.props.dispatch({
        //   type: 'stat/fetchStatBranchRateCurYear',
        //   payload: {},
        // });
        // this.props.dispatch({
        //   type: 'stat/fetchStatBranchRateCurMonth',
        //   payload: {},
        // });
        break;
      case '3':
        this.props.dispatch({
          type: 'stat/fetchStatTasks',
          payload: {},
        });
        break;
      default:
    }
  };

  getFlag = (v) => {
    switch (v) {
      case 1:
        return <MyIcon type="flag" />;
      case 2:
        return <MyIcon type="flag_yellow" />;
      case 3:
        return <MyIcon type="flag_blue" />;
      default:
        return v;
    }
  };

  showSalesmanVisit = (item, isType) => {
    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let maskProps;
    if (isIPhone) {
      // Note: the popup content will not scroll.
      maskProps = {
        onTouchStart: e => e.preventDefault(),
      };
    }
    Popup.show(<div>
      <List
        renderHeader={() => {
          return item.name;
        }
        }
        className="popup-list"
      >
        <ListItem extra={`${item.nv}人`}>应回访客户数</ListItem>
        <ListItem extra={`${item.cv}人`}>实际回访客户数</ListItem>
        <ListItem extra={`${item.sv}人`}>{isType ? '回访成功客户数' : '转化成功客户数'}</ListItem>
        <ListItem extra={`${item.value}%`}>{isType ? '回访完成率' : '转化成功率'}</ListItem>
      </List>

    </div>, { animationType: 'slide-up', maskProps: null, maskClosable: true });
  };

  onRank1Sort = (opt) => {
    this.setState({
      rank1Sort: { key: opt.key, sort: opt.sort },
    });
  };

  onRank2Sort = (opt) => {
    this.setState({
      rank2Sort: { key: opt.key, sort: opt.sort },
    });
  };

  click = (type) => {
    this.props.dispatch(routerRedux.push({
      pathname: '/myTasksContent',
      query: {
        type,
        isBranch: true,
      },
    }));
  }

  renderStatTask = () => {
    const { statTasks, branchPickerValue } = this.props;
    if (!statTasks || !statTasks.rank) return null;
    const { rank1, rank2 } = statTasks.rank;

    const { key: rank1Key, sort: rank1Sort } = this.state.rank1Sort;
    const { key: rank2Key, sort: rank2Sort } = this.state.rank2Sort;
    const sortRank1 = _.orderBy(rank1, [rank1Key], [rank1Sort === -1 ? 'desc' : 'asc']);
    const sortRank2 = _.orderBy(rank2, [rank2Key], [rank2Sort === -1 ? 'desc' : 'asc']);
    return (
      <div>

        <div>
          {/* <p style={{ textAlign: 'center' }}>整体回访情况</p>*/}
          <List
            renderHeader={() =>
              <div>
                当月或者全部月份整体回访情况
                {/* <SegmentedControl selectedIndex={1}
                 values={['昨日', '本月', '累计']} className={styles.segment}/>*/}
              </div>
            }
          >
            <ListItem
              extra={`${statTasks.needCount}人`} onClick={this.click.bind(this, 5)}
              arrow="horizontal"
            >应回访客户数</ListItem>
            <ListItem
              extra={`${statTasks.count}人`} onClick={this.click.bind(this, 2)}
              arrow="horizontal"
            >实际回访客户数</ListItem>
            <ListItem
              extra={`${statTasks.successCount}人`} onClick={this.click.bind(this, 3)}
              arrow="horizontal"
            >转化成功客户数</ListItem>
            <ListItem
              extra={`${statTasks.realCount}人`} onClick={this.click.bind(this, 1)}
              arrow="horizontal"
            >待回访客户数</ListItem>
            <ListItem
              extra={`${statTasks.expiredCount}人`} onClick={this.click.bind(this, 4)}
              arrow="horizontal"
            >过期任务数</ListItem>
            <ListItem extra={`${statTasks.completePercentage || 0}%`}>回访完成率</ListItem>
            <ListItem extra={`${statTasks.successPercentage || 0}%`}>转化成功率</ListItem>
            <ListItem extra={`${statTasks.successTotalMoney.toFixed(2) || 0}`}>转化金额</ListItem>
            {/* <ListItem extra={`${statTasks.needCount}人`}>回访贡献</ListItem>*/}
          </List>

        </div>

        <WhiteSpace size="lg" />
        <p style={{ textAlign: 'center' }}>员工排名</p>
        <div>
          <WingBlank size="sm">
            <Tabs defaultActiveKey="1" swipeable={false}>
              <TabPane tab="回访完成率" key="1">
                <div>
                  <List
                    renderHeader={() =>
                      <SortableListHead
                        defaultSort={-1} columns={
                        [
                          { title: '排名', sort: false, style: { flex: 1.2 } },
                          { title: '姓名', sort: false, style: { flex: 1 } },
                          { title: '完成人数', key: 'cv', style: { flex: 1 } },
                          { title: '完成率', key: 'value', sort: -1, style: { flex: 1 } },
                        ]}
                        onSortChange={this.onRank1Sort}
                      />
                    }
                  >
                    {sortRank1.map((item, index) => {
                      return (
                        <ListItem
                          key={`rank1-${index}`}
                          onClick={() => {
                            this.showSalesmanVisit(item, 1);
                          }}
                        >
                          <div className={styles.header}>
                            <span className={styles.header_item}>{this.getFlag(index + 1)}</span>
                            <span className={styles.header_span1}>{item.name}</span>
                            <span className={styles.header_span1}>{item.cv}</span>
                            <span className={styles.header_span1}>{item.value}%</span>
                          </div>
                        </ListItem>
                      );
                    })}
                  </List>
                </div>
              </TabPane>

              <TabPane tab="转化成功率" key="2">
                <div>
                  <List
                    renderHeader={() =>
                      <SortableListHead
                        defaultSort={-1} columns={
                        [
                          { title: '排名', sort: false, style: { flex: 1 } },
                          { title: '姓名', sort: false, style: { flex: 1 } },
                          { title: '转化人数', key: 'sv', style: { flex: 1.5 } },
                          { title: '转化金额', key: 'money', style: { flex: 1.5 } },
                          { title: '成功率', key: 'value', sort: -1, style: { flex: 1.2 } },
                        ]}
                        onSortChange={this.onRank2Sort}
                      />
                    }
                  >
                    {sortRank2.map((item, index) => {
                      return (
                        <ListItem
                          key={`rank2-${index}`}
                          onClick={() => {
                            this.showSalesmanVisit(item);
                          }}
                        >
                          <div className={styles.header}>
                            <span className={styles.header_item1}>{this.getFlag(index + 1)}</span>
                            <span className={styles.header_span1}>{item.name}</span>
                            <span className={styles.header_span2}>{item.sv}</span>
                            <span className={styles.header_span3}>{item.money}</span>
                            <span className={styles.header_span1}>{item.value}%</span>
                          </div>
                        </ListItem>
                      );
                    })}
                  </List>
                </div>
              </TabPane>

              {/*
               <TabPane tab="回访业绩" key="3">
               <div>

               <List
               renderHeader={() =>
               <div className={styles.header}>
               <span className={styles.header_item} style={{ marginLeft: 20 }}>
               排名
               </span>
               <span className={styles.header_span1}>姓名</span>
               <span className={styles.header_span1}>业绩(元)</span>
               </div>}
               >
               <ListItem
               onClick={() => {
               }}
               >
               <div className={styles.header}>
               <span style={{ width: 30 }}><MyIcon type="flag"/></span>
               <span className={styles.header_item}>1</span>
               <span className={styles.header_span1}>张华</span>
               <span className={styles.header_span1}>45020</span>
               </div>
               </ListItem>
               <ListItem>
               <div className={styles.header}>
               <span style={{ width: 30 }}><MyIcon type="flag_yellow"/></span>
               <span className={styles.header_item}>2</span>
               <span className={styles.header_span1}>张华</span>
               <span className={styles.header_span1}>45020</span>
               </div>
               </ListItem>
               <ListItem>
               <div className={styles.header}>
               <span style={{ width: 30 }}><MyIcon type="flag_blue"/></span>
               <span className={styles.header_item}>3</span>
               <span className={styles.header_span1}>张华</span>
               <span className={styles.header_span1}>45020</span>
               </div>

               </ListItem>
               <ListItem>
               <div className={styles.header}>
               <span style={{ width: 30 }}/>
               <span className={styles.header_item}>4</span>
               <span className={styles.header_span1}>张华</span>
               <span className={styles.header_span1}>45020</span>
               </div>
               </ListItem>
               <ListItem>
               <div className={styles.header}>
               <span style={{ width: 30 }}/>
               <span className={styles.header_item}>5</span>
               <span className={styles.header_span1}>张华</span>
               <span className={styles.header_span1}>45020</span>
               </div>
               </ListItem>
               </List>
               </div>
               </TabPane>
               */}

            </Tabs>
          </WingBlank>
        </div>

      </div>
    );
  };

  renderStatBranchRateCurYear = () => {
    const { branchList, statBranchRateCurYear, form, roles, branchPickerValue } = this.props;
    return (
      <List
        renderHeader={() => `截至${branchPickerValue[1] ? moment(branchPickerValue[1]).format('YYYY-MM') : '昨日'}，全年完成销售额${statBranchRateCurYear ? statBranchRateCurYear.totalmoney : 0}万元，
        完成进度${statBranchRateCurYear ? statBranchRateCurYear.rate : 0}`}
      >
        <ListItem>
          {this.getOption4()}
        </ListItem>
      </List>
    );
  };

  renderStatBranchRateCurMonth = () => {
    const { branchList, statBranchRateCurMonth, form, roles, branchPickerValue } = this.props;
    // if (!statBranchRateCurMonth) return null;
    return (
      <List
        renderHeader={() => `截至${branchPickerValue[1] ? moment(branchPickerValue[1]).format('YYYY-MM') : '昨日'}，当月完成销售额${statBranchRateCurMonth ? statBranchRateCurMonth.totalmoney : 0}万元，
        完成进度${statBranchRateCurMonth ? statBranchRateCurMonth.rate : 0}`}
      >
        <ListItem>
          {this.getOption3()}
        </ListItem>
      </List>
    );
  };

  timeout = (ms) => {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, ms, 'done');
    });
  }

  filterControlsChange = async (v) => {
    await this.timeout(10);
    const branchNo = v[0] !== '全部' ? v[0] : undefined;
    const endDate = moment(v[1]).add(1, 'months').startOf('month').format('YYYY-MM-DD');

    {
      const startDate = moment(v[1]).startOf('month').format('YYYY-MM-DD');
      this.props.dispatch({
        type: 'stat/fetchStatBranchRateCurMonth',
        payload: { branchId: branchNo, startDate, endDate },
      });
    }

    {
      const startDate = moment(v[1]).startOf('year').format('YYYY-MM-DD');
      this.props.dispatch({ type: 'stat/fetchStatBranchRateCurYear', payload: { branchId: branchNo, startDate, endDate } });
    }

    {
      if (v[1] !== '全部') {
        const startDate = moment(v[1]).startOf('month').format('YYYY-MM-DD');
        this.props.dispatch({
          type: 'stat/fetchStatTasks',
          payload: { branchNo, startDate, endDate },
        });
      } else {
        this.props.dispatch({
          type: 'stat/fetchStatTasks',
          payload: { branchNo },
        });
      }
    }
  }

  componentDidMount() {
    let { branchPickerValue } = this.props.stat;
    branchPickerValue = branchPickerValue.length ? branchPickerValue : ['全部', moment().format('YYYY-MM')];
    this.filterControlsChange(branchPickerValue);
  }

  render() {
    return (
      <Container title="销售管理">
        <div>
          <Tabs defaultActiveKey="2" swipeable={false}>
            <TabPane tab="销售监控" key="2">
              <div>
                <FilterControl
                  filterControlsChange={this.filterControlsChange} dispatch={this.props.dispatch}
                  hidePickerDate={false}
                />
                {this.renderStatBranchRateCurMonth()}
                {this.renderStatBranchRateCurYear()}
              </div>

            </TabPane>
            <TabPane tab="回访监控" key="3">
              <FilterControl
                filterControlsChange={this.filterControlsChange} dispatch={this.props.dispatch}
                hidePickerDate={false} showDateAll
              />
              {this.renderStatTask()}
            </TabPane>
          </Tabs>
        </div>

      </Container>
    );
  }
}

export default connect((state) => {
  return {
    statTasks: state.stat.statTasks,
    statBranchRateCurYear: state.stat.statBranchRateCurYear,
    statBranchRateCurMonth: state.stat.statBranchRateCurMonth,
    branchList: state.stat.branchList,
    roles: state.auth.currentUser.roles,
    branchPickerValue: state.stat.branchPickerValue,
    stat: state.stat,
  };
})(createForm()(PerformancePage));
